var carousel = document.querySelector(".carousel");
var items = document.querySelector(".items");
var itemList = document.querySelectorAll(".item");
var navList = document.querySelectorAll(".nav li");

items.style.width = carousel.clientWidth * itemList.length + "px";
items.style.marginLeft = "0px";

var startX;
var index = 0;
var startLeft = 0;
var stop = false;

items.addEventListener("touchstart", function (e) {
    items.style.transition = "";
    startX = e.changedTouches[0].clientX;
    startLeft = parseInt(items.style.marginLeft);
    stop = true;
})

items.addEventListener("touchmove", function (e) {
    var nowX = e.changedTouches[0].clientX;
    items.style.marginLeft = (startLeft + (nowX - startX)) + "px";
})

items.addEventListener("touchend", function (e) {
    var nowX = e.changedTouches[0].clientX;
    if (Math.abs(nowX - startX) >= carousel.clientWidth / 2) {
        index += -Math.sign(nowX - startX);
        if (index < 0) {
            index = 0;
        } else if (index >= itemList.length) {
            index = itemList.length - 1;
        }
    }
    moveToItem();
    stop = false;
})

function moveToItem() {
    items.style.transition = "all .5s";
    items.style.marginLeft = -(index * carousel.clientWidth) + "px";
    for (let i = 0; i < navList.length; i++) {
        navList[i].classList.remove("active");
    }
    navList[index < navList.length ? index : index - navList.length].classList.add("active");
}

setInterval(function () {
    if (stop) {
        return;
    }
    index++;
    if (index >= itemList.length) {
        index = 0;
    }
    moveToItem();
}, 2000);